package com.sqoq.downloader3

import android.app.Activity
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.GravityCompat
import androidx.core.view.children
import androidx.core.view.isVisible
import com.sqoq.downloader3.base_ddg.BaseActivity_ddg
import com.sqoq.downloader3.databinding.ActivityMainBinding
import com.sqoq.downloader3.lanuage_ddg.StringId_ddg
import com.sqoq.downloader3.retrofit.ParameterMap
import com.sqoq.downloader3.ui.DetaileActivity_ddg
import com.sqoq.downloader3.ui.DownloadActivity_ddg
import com.sqoq.downloader3.ui.StepDialogFragment_ddg
import com.sqoq.downloader3.ui.WebActivity_ddg
import kotlinx.coroutines.Job


class MainActivity : BaseActivity_ddg<ActivityMainBinding>() {


    private var job: Job? = null
    var text = ""
    override val layout: Int
        get() = R.layout.activity_main

    override fun initView() {
        binding.shareAppDdg.setOnClickListener {
            val intent = Intent(Intent.ACTION_SEND) //发送多个文件
            intent.type = "text/plain" //多个文件格式
            intent.putExtra(Intent.EXTRA_SUBJECT, "")

            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.putExtra(
                Intent.EXTRA_TEXT,
                "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID
            )
            startActivity(intent)
        }
        binding.privacyPolicyDdg.setOnClickListener {
            WebActivity_ddg.start(
                baseContext,
                App.PrivacyPolicy_ddg,
                getLanguageString_ddg(StringId_ddg.PrivacyPolicy_ddg)
            )
        }
        binding.settingDdg.setOnClickListener {
            binding.drawerLayout.open()
        }
        binding.downloadDdg.setOnClickListener {
            startActivity(DownloadActivity_ddg::class.java)
        }
        binding.helpDdg.setOnClickListener {

            StepDialogFragment_ddg().show(supportFragmentManager, "StepDialogFragment_ddg")
        }
        binding.textDdg.children.forEachIndexed { index, view ->
            view.setOnClickListener {
                setSelect(index)
            }
        }
        setSelect(0)
        binding.btnDdg.setOnClickListener {
            var clipboardManager =
                getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            if (clipboardManager.hasPrimaryClip()) {
                var clipData = clipboardManager.getPrimaryClip();
                if (clipData != null && clipData.getItemCount() > 0) {
                    if ((clipData.getItemAt(0).text.toString() != text && clipData.getItemAt(0).text != null)) {
                        text = clipData.getItemAt(0).text.toString()
                        binding.tvContentDdg.setText(text)
                    }
                }
            }
            hideSoftInput()
            paste()
        }

        intent?.getStringExtra("path_ddg")?.let {
            binding.tvContentDdg.setText(it)
            paste()
        }
        setPath(intent)
    }

    fun paste() {
        if (binding.tvContentDdg.text.toString().trim().isEmpty()) {
            return
        }
        job?.cancel()
        binding.progressDdg.isVisible = true
        var map = ParameterMap()
        map["url"] = binding.tvContentDdg.text.toString().trim()
        job = request(apiCall = {
            App.apiService.pasteVideo_ddg(map.toRequestBody())
        }, onStart = {
            binding.progressDdg.isVisible = true
        }, onSuccess = {
            if (it.status_ss == "1") {
                startActivity(DetaileActivity_ddg::class.java, argument = { intent ->
                    intent.putExtra("data", it)

                })
            } else {
                Toast.makeText(
                    baseContext,
                    getLanguageString_ddg(StringId_ddg.paste2_ddg),
                    Toast.LENGTH_SHORT
                ).show()
            }

        }, onComplete = {

            binding.progressDdg.isVisible = false
        }, onHttpError = {
            Toast.makeText(
                baseContext,
                getLanguageString_ddg(StringId_ddg.paste2_ddg),
                Toast.LENGTH_SHORT
            ).show()
        })


    }

    fun setSelect(index: Int) {
        binding.textDdg.children.forEachIndexed { index2, view ->

            kotlin.runCatching {
                if (view is TextView) {
                    view.setTextColor(
                        if (index == index2) Color.parseColor("#FFFFFFFF") else Color.parseColor(
                            "#FF575757"
                        )
                    )

                }

                if (index == index2) {
                    view.setBackgroundResource(R.drawable.me2_ddg)
                } else {
                    view.setBackgroundColor(Color.TRANSPARENT)
                }
            }
        }
    }

    override fun onBackPressed() {
        if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            binding.drawerLayout.closeDrawer(GravityCompat.START)
            return
        }
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        hideSoftInput()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setPath(intent)

    }

    fun setPath(intent: Intent?) {
        intent?.getStringExtra("path_ddg")?.let {
            binding.tvContentDdg.setText(it)

            paste()
        }
    }

}

fun Activity.hideSoftInput() {
    kotlin.runCatching {
        if (currentFocus != null) {
            if (currentFocus!!.windowToken != null) {
                (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
                    .hideSoftInputFromWindow(
                        currentFocus!!.windowToken,
                        InputMethodManager.HIDE_NOT_ALWAYS
                    )
            }
        }
    }
}